package com.dragon.web.commons.controller;



import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;



public class BaseController extends WebMvcConfigurerAdapter {
	
	public static HttpServletRequest  getCurrentRequest(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		return request;
	}
	
	/**
	 * 获取请求头消息
	 * @return
	 */
	protected Map<String,String> getHeaders(){
		HttpServletRequest request =  getCurrentRequest();
//		Enumeration<String>
		Map<String,String> headers = new HashMap<String,String>();
		Enumeration<String> headerNamesEnum = request.getHeaderNames();
		while(headerNamesEnum.hasMoreElements()){
			String hearderName = headerNamesEnum.nextElement();
			headers.put(hearderName, request.getHeader(hearderName));
		}
		return headers;
	}
	
	public static HttpSession getCurrentSession(){
		return getCurrentRequest().getSession();
	}
	/**
	 * 获得当前请求IP
	 * @return
	 */
	public static String getIpAddr() {  
		HttpServletRequest request=getCurrentRequest();
        String ip = request.getHeader("X-Forwarded-For");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }  
	
/*	public static User getCurrentUser(String token){
		String user_info=RedisUtils.getInstance().get(token);
		User result_user = (User)JSONObject.toBean(JSONObject.fromObject(user_info), User.class);
		return result_user;
	}*/
	/**
	 * 设置页面输出的编码
	 * @param response
	 * @return
	 */
	public static PrintWriter getOut(HttpServletResponse response){
		PrintWriter r = null;
		try {
			response.setContentType("text/html;charset=UTF-8");
			r = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return r;
	}
	
}
